package io.gitee.hechenl.fastiotreport.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import io.gitee.hechenl.fastiotreport.controller.converter.ConfigPointConverter;
import io.gitee.hechenl.fastiotreport.domain.dto.ImportPointDTO;
import io.gitee.hechenl.fastiotreport.domain.dto.PointListDTO;
import io.gitee.hechenl.fastiotreport.domain.vo.PointListVO;
import io.gitee.hechenl.fastiotreport.service.IConfigPointService;
import io.gitee.hechenl.fastiotreport.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

@RequestMapping("/config/point")
@RestController
public class ConfigPointController {

    @Autowired
    private IConfigPointService pointService;

    @PostMapping("/import")
    public Result<Void> importExcel(@RequestParam("file") MultipartFile file) {
        List<ImportPointDTO> cacheList = new ArrayList<>();
        try {
            EasyExcel.read(file.getInputStream(), ImportPointDTO.class, new ReadListener<ImportPointDTO>() {
                        @Override
                        public void invoke(ImportPointDTO dto, AnalysisContext analysisContext) {
                            cacheList.add(dto);
                            // 每50条处理一次
                            if (cacheList.size() >= 50) {
                                pointService.insert(ConfigPointConverter.toInsertModelList(cacheList));
                                cacheList.clear();
                            }
                        }
                        @Override
                        public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                            pointService.insert(ConfigPointConverter.toInsertModelList(cacheList));
                        }
                    })
                    .sheet()
                    .doRead();
            return Result.success();
        } catch (Exception e) {
            return Result.error(500,"导入失败: " + e.getMessage());
        }
    }

    @GetMapping("/list")
    public Result<List<PointListVO>> list(PointListDTO dto) {
        return Result.success(ConfigPointConverter.toVOList(pointService.list(dto.getPointId(), dto.getPointName())));
    }
}
